import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: [
      { id: 1, name: '手机', price: 1000, quantity: 1 },
      { id: 2, name: '电脑', price: 2000, quantity: 1 },
      { id: 3, name: '键盘', price: 200, quantity: 2 }
    ]
  },
  mutations: {
    addToCart(state, product) {
      state.cart.push(product)
    },
    removeFromCart(state, productId) {
      state.cart = state.cart.filter(item => item.id !== productId)
    },
    updateQuantity(state, { productId, quantity }) {
      const product = state.cart.find(item => item.id === productId)
      if (product) {
        product.quantity = quantity
      }
    }
  },
  actions: {
    addToCart({ commit }, product) {
      commit('addToCart', product)
    },
    removeFromCart({ commit }, productId) {
      commit('removeFromCart', productId)
    },
    updateQuantity({ commit }, { productId, quantity }) {
      commit('updateQuantity', { productId, quantity })
    }
  },
  getters: {
    totalPrice: state => {
      return state.cart.reduce((total, item) => total + item.price * item.quantity, 0)
    }
  }
})